package com.cmq.web_1.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;


public class LogFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String method = httpRequest.getMethod();
        String requestURI = httpRequest.getRequestURI();
        String queryString = httpRequest.getQueryString();
        if (queryString != null) {
            requestURI += "?" + queryString;
        }
        System.out.println("【日志】收到请求：" + method + " " + requestURI);

        chain.doFilter(request, response); // 调用下一个过滤器（或Servlet）

        Long elapsedTime = (Long) request.getAttribute("elapsedTime"); // 读取性能监控的耗时
        String timeInfo = elapsedTime != null ? "，耗时：" + elapsedTime + " 毫秒" : "";
        System.out.println("【日志】请求结束" + timeInfo);
    }

    @Override
    public void destroy() {}
}
